package com.manage.tasks;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.TimerTask;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.manage.func.activity.dao.IActivityDao;
import com.manage.func.activity.model.ActExpireBean;
import com.manage.util.SpringApplicationContextHolder;

/**
 * 活动过期状态检测线程
 * 
 * @author suid
 *
 */
public class ActCheckTask extends TimerTask {

	static final Logger LOG = LoggerFactory.getLogger(ActCheckTask.class);

	String name;
	public boolean runFlag = true;
	private IActivityDao actDao;

	@Override
	public void run() {
		try {
			actDao = SpringApplicationContextHolder.getSpringBeanByType(IActivityDao.class);
			while (actDao == null) {
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
				}
				actDao = SpringApplicationContextHolder.getSpringBeanByType(IActivityDao.class);
			}
			if (runFlag) {
				actExpireCheck();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 根据当前时间来判断活动的过期状态
	 */
	private void actExpireCheck() {
		// 1. 读取当前活动状态expire
		// 2. 判断当前时间<开始时间， 则置活动状态为0，未开始 (前提是活动的状态不为0)
		// 3. 判断当前>开始 && 当前<结束，则设置活动状态1(前提是活动的状态不为1)
		// 4. 如果当前>结束，则设置活动状态为2(前提是活动的状态不为2)
		Long curr = System.currentTimeMillis();
		Long start = 0L;
		Long end = 0L;
		List<ActExpireBean> upBeans = new ArrayList<ActExpireBean>();
		List<ActExpireBean> lists = actDao.expireSelect();
		if (lists != null && !lists.isEmpty()) {
			for (ActExpireBean bean : lists) {
				if ((bean.endTime != null && !bean.endTime.equals(""))
						&& (bean.startTime != null && !bean.startTime.equals(""))) {
					start = Timestamp.valueOf(bean.startTime).getTime();
					end = Timestamp.valueOf(bean.endTime).getTime();
					if (curr < start && bean.expire != 0) {
						LOG.info("update activity : 0 id = " + bean.activityId);
						bean.expire = 0;
						upBeans.add(bean);
					} else if (curr >= start && curr < end && bean.expire != 1) {
						LOG.info("update activity : 1 id = " + bean.activityId);
						bean.expire = 1;
						upBeans.add(bean);
					} else if (curr >= end && bean.expire != 2) {
						LOG.info("update activity : 2 id = " + bean.activityId);
						bean.expire = 2;
						upBeans.add(bean);
					}
				}
			}
		}

		for (ActExpireBean bean : upBeans) {
			actDao.expireUpdate(bean);
		}
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public static void main(String[] args) {
		System.out.println(Timestamp.valueOf("2015-04-30 23:33:12"));
	}

}
